package com._520it.wms.web.interceptor;

import com._520it.wms.domain.Employee;
import com._520it.wms.util.RequiredPermission;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

//权限拦截器
public class SecurityIntercetor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod hm = (HandlerMethod) handler;
        Employee currentUser = (Employee) request.getSession().getAttribute("USER_IN_SESSION");
        //1判断是否是超级管理员
        if (currentUser.getAdmin()) {
            return true;
        }
        //2判断方法是否需要权限控制


        RequiredPermission rp = hm.getMethod().getAnnotation(RequiredPermission.class);
        if (rp == null) {
            return true;
        }

        // 3获取权限的表达式 类权限:方法名字
        String experssion = hm.getBeanType().getName() + ":" + hm.getMethod().getName();
        List<String> permissionList = (List<String>) request.getSession().getAttribute("PERMISSION_IN_SESSION");
        if (permissionList != null && permissionList.contains(experssion)) {
            return true;//拥有权限
        }
        // 4没有权限
        throw new SecurityException("没有权限操作");
    }
}
